#coding=utf-8
import base64
import hashlib 
import hmac 
import json 
import time 
import logging 
import requests
import mysql.connector
import datetime
import guji
import by
import gdt
import postYx
import toke
import ccTell

crm_server = 'https://crm.bytedance.com' 
pull_clues_api = '/crm/v2/openapi/pull-clues/'

class Signature(object):

	def __init__(self, signature_header=None, timestamp_header=None, timeout=None, token_header=None, digestmod=None):		  
		self.signature_header = signature_header or 'Signature'		   
		self.timestamp_header = timestamp_header or 'Timestamp'		   
		self.token_header = token_header or 'Access-Token'		  
		self.timeout = timeout or 300		 
		self.digestmod = digestmod or hashlib.sha256		
		self.signature_key = 'SEExMUJCMDBPQURJ' 
		self.token = 'd23360ab2891baf0bb8ad76e2504dc0a484eb200'
		# token
	def generate_signature(self, data, key=None):
		key = key if key else self.signature_key 
		key=bytes(key,'utf-8')
		data=bytes(data,'utf-8')
		signature = hmac.new(key, data,digestmod=self.digestmod). hexdigest()
		signature=bytes(signature,'utf-8')		  
		signature = base64.b64encode(signature)		   
		return signature

def crm_pull_clues(start_time, end_time, signature_key,token,page=1, page_size=10):
	payload = {}
	payload["start_time"] = start_time
	payload["end_time"] = end_time
	payload["page"] = page
	payload["page_size"] = page_size	
	timestamp = str(int(time.time()))	 
	sig = Signature()
	sig.signature_key=signature_key
	sig.token=token
	url = crm_server + pull_clues_api 
	data = sig.generate_signature('/crm/v2/openapi/pull-clues/?start_time=%s&end_time=%s %s' % (start_time, end_time, timestamp))	 
	headers = {sig.signature_header: data, sig.timestamp_header: timestamp, sig.token_header: sig.token}	
	headers.update({'Content-Type': 'application/json'})	
	max_tries = 3
	resp_data = None
	while max_tries > 0:		
		try:
			#print (payload)
			resp = requests.get(url=url, params=payload, headers=headers)
			if resp.status_code == 200:
				res = json.loads(resp.content)	   # 
				if res:
				   return res
		except Exception as e:
			logging.exception("error with %s" % str(e))
			resp_data = None
		max_tries -= 1
	return resp_data
def zuoTian():
	today = datetime.datetime.now()
	offset = datetime.timedelta(days=-1)
	re_date = (today + offset).strftime('%Y-%m-%d')
	return re_date
#591的抖音
#SEExMUJCMDBPQURJ
#token：d23360ab2891baf0bb8ad76e2504dc0a484eb200
#智迪的抖音
#RkFUSE1FN1BXNzdH
#852a85cc100435e81af62b12d017576f33039e79

def getFeiYuData():
	dangQiandate=time.strftime("%Y-%m-%d") ##24小时格式
	print('斗音调取数据日期：'+zuoTian()+'-'+dangQiandate)
	res_wjy = crm_pull_clues(start_time=zuoTian(),end_time=dangQiandate, signature_key='SEExMUJCMDBPQURJ',token='d23360ab2891baf0bb8ad76e2504dc0a484eb200')#591的抖音
	res_zd = crm_pull_clues(start_time=zuoTian(),end_time=dangQiandate, signature_key='RkFUSE1FN1BXNzdH',token='852a85cc100435e81af62b12d017576f33039e79')#智迪的抖音
	if res_wjy.get("status") == "success":
		data = res_wjy.get("data") or []
		if res_wjy.get("count") > 10:
				count = res_wjy.get("count")
				times = int(count / 10)+2
				#print(times)
				for i in range(2,times): #10 
					#print(i)
					res = crm_pull_clues(start_time=zuoTian(),end_time=dangQiandate,page=i, signature_key='SEExMUJCMDBPQURJ',token='d23360ab2891baf0bb8ad76e2504dc0a484eb200')
					data = data + res.get("data")
	# print(len(data))
	#print(res_zd)
	if res_zd.get("status") == "success":
		data1 = res_zd.get("data") or []
		#print(len(data1))
		if res_zd.get("count") > 10:
				count = res_wjy.get("count")
				times = int(count / 10)+2
				for i in range(2,times): #10 
					res = crm_pull_clues(start_time=zuoTian(),end_time=dangQiandate,page=i, signature_key='RkFUSE1FN1BXNzdH',token='852a85cc100435e81af62b12d017576f33039e79')
					data1 = data1 + res.get("data")
	#print(len(data1))
	return data+data1

def upDb():

	mydb = mysql.connector.connect(
	  host="localhost",       # 数据库主机地址
	  user="root",    # 数据库用户名
	  passwd="root",   # 数据库密码
	  database="weizandata"
	)

	mycursor = mydb.cursor()
	upCount=0
	for item in getFeiYuData():

		val=[]
		filed=[]
		for key in item:
			filed.append(key)
			val.append('\"'+str(item[''+key+''])+'\"')

		filedStr=','.join(filed)
		valStr=','.join(val)
		# print(item['adv_id'])
		if item['adv_id'] == '1671616657392654':
			sql="INSERT IGNORE INTO douYinDbPhone("+filedStr+",submit_date,qudao)value("+valStr+",\""+str(time.strftime("%Y-%m-%d %H:%M:%S"))+"\",\"1280446893134057472\");"
		elif item['adv_id'] == '1671609230141448':
			sql="INSERT IGNORE INTO douYinDbPhone("+filedStr+",submit_date,qudao)value("+valStr+",\""+str(time.strftime("%Y-%m-%d %H:%M:%S"))+"\",\"1280447044984639488\");"
		# print(sql+'\n')
		mycursor.execute(sql)
		upCount=upCount+int(mycursor.rowcount)
		mydb.commit()
	return upCount
def sleeptime(hour,min,sec):
	return hour*3600 + min*60 + sec;



if __name__ == '__main__':
	#print(len(getFeiYuData()))
	#print(upDb())
	count=0;
	obj1=guji.guiJi()
	gdt1=gdt.gdt()
	# print('第'+str(count)+'次调取，时间')
	# print(time.strftime("%Y-%m-%d %H:%M:%S"))
	# print('硅基更新：'+str(obj1.upDb()))
	# print('抖音更新：'+str(upDb()))
	byget=by.by()
	# byget.byupData()
	# gdt1.getGdt()
	second = sleeptime(0,0,5);
	errorCount=1
	cc=ccTell.cc()

	data=cc.getYouju(10)

	byget.byupData()

	
	while 1==1:

		try:
			
			time.sleep(second);
			count=count+1

			print('第'+str(count)+'次调取，时间')
			print(time.strftime("%Y-%m-%d %H:%M:%S"))
			#print("转单==>",cc.getZhuanDan(20))
			# data=cc.getYouju(10) #优居朋友圈线索获取
			# gdt1.getGdt('171887411595049713','ceabc0d2cc630c37be55c6cb23b4161b','1284016882717954048');#广点通-591
			# gdt1.getGdt('171764841595465948','928d32ea9b68307bc947089315edb8d1','1122785705056145408');#广点通-优居朋友圈
			# print('硅基更新：'+str(obj1.upDb()))
			# print('抖音更新：'+str(upDb()))
			byget.byupData()

			

			if errorCount==0:

				yx=postYx.yx()

				to_list = ['450537144@qq.com'] #多用户使用的list
     
				yx.Mailer(to_list,th1="您的python脚本feiyuApi.py恢复正常运行",Subject='服务器正常提示')#,unipath=r'F:\test.xlsx'

				errorCount=1

		except:

			if(errorCount==1):

				yx=postYx.yx()

				to_list = ['450537144@qq.com'] #多用户使用的list
     
				yx.Mailer(to_list,th1="您的python脚本feiyuApi.py出现故障请及时处理",Subject='服务器故障报警')#,unipath=r'F:\test.xlsx'

				errorCount=0

			print('error')

		
	#这是隔10分钟执行一次

